package com.wealth.lottery.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.lottery.entity.LotteryActivity;
import com.wealth.lottery.entity.LotteryPrize;
import com.wealth.lottery.enums.LotteryActivityPrizeEnums;
import com.wealth.lottery.enums.LotteryActivityStatusEnums;
import com.wealth.lottery.enums.LotteryActivityTypeEnums;
import com.wealth.lottery.enums.LotteryPurposeEnums;
import com.wealth.lottery.service.ILotteryActivityService;
import com.wealth.lottery.service.ILotteryPrizeService;
import com.wealth.lottery.service.ILotteryRecordService;
import com.wealth.lottery.util.RandomLotteryLuckNum;
import com.wealth.platform.service.ISldConfigService;
import com.wealth.system.entity.Corporation;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;
/**
 * 抽奖活动管理controller
 * @author lihang 2016-06-27
 *
 */
@Controller
@RequestMapping(value="manage/lottery")
public class LotteryController extends BaseController{
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		//注册自定义的属性编辑器，适合日期
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		// 表示如果命令对象有Date类型的属性，将使用该属性编辑器进行类型转换
		binder.registerCustomEditor(Date.class, dateEditor);
	}
	//日志记录对象
	Logger logger = Logger.getLogger(LotteryController.class);
	//注入ILotteryActivityService
	@Autowired
	private ILotteryActivityService activityService;
	@Autowired
	private ILotteryPrizeService iLotteryPrizeService;
	@Autowired
	private ILotteryRecordService iLotteryRecordService; // 抽奖记录
	@Autowired 
	private ISldConfigService configService;
	/**
	 * 进入列表页面
	 * @return ftl页面
	 * @author lihang 2016-06-27
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String toList(Model model){
		model.addAttribute("lotteryActivityEnum", LotteryActivityStatusEnums.values());
		return "lottery/list";
	}
	/**
	 * 得带列表数据 ajax请求
	 * @param model
	 * @param request
	 * @return
	 * @author lihang 2016-06-27
	 */
	@RequestMapping(value="/list",method=RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getList(Model model,JqGridRequest request) {
		try{
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			Page<LotteryActivity> page = activityService.get(corpid, request,LotteryActivity.class);
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	/**
	 * 跳转创建抽奖活动页面
	 * @return ftl页面
	 * @author lihang 2016-06-27
	 */
	@RequestMapping(value="create",method=RequestMethod.GET)
	public String tocreate(Model model){
		model.addAttribute("scoretypeList", LotteryPurposeEnums.values());
		model.addAttribute("typeList", LotteryActivityTypeEnums.values());
		model.addAttribute("statusList", LotteryActivityStatusEnums.values());
		model.addAttribute("prizetypeList",LotteryActivityPrizeEnums.values());
		return "lottery/create";
	}
	
	@RequestMapping(value="createurl/{id}",method=RequestMethod.GET)
	public String tocreateurl(Model model,@PathVariable Long id){
		 try {
			model.addAttribute("id", id);
			model.addAttribute("sldList", configService.getSldConfidAndCorpIdNotNoe());
			return "lottery/createUrl";
		} catch (Exception e) {
			return "system/500";
		}
	}
	/**
	 * 创建完成回到列表页面
	 * @return 重定向controller链接
	 * @author lihang 2016-06-28
	 */
	@RequestMapping(value="upcreate",method=RequestMethod.POST)
	public String create(Model model,LotteryActivity lottery){
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			//if(lottery.getScoretype()==LotteryPurposeEnums.CURRENCY.getValue()&&lottery.getStatus()== LotteryActivityStatusEnums.NORMAL.getValue()){
				/**停用所有其他的通用抽奖活动*/
			if(lottery.getStatus()== LotteryActivityStatusEnums.NORMAL.getValue()){	
				List<LotteryActivity> activityList=activityService.findByCorpIdAndStatus(corpid,LotteryActivityStatusEnums.NORMAL.getValue());
				if(activityList.size()>0){
					for (LotteryActivity lotteryActivity : activityList) {
						lotteryActivity.setStatus(LotteryActivityStatusEnums.STOP.getValue());
						activityService.save(lotteryActivity);
					}
				}
			}
			//保存活动
			lottery.setCorp(new Corporation(corpid));
			lottery.setCreateTime(new Date());
			lottery.setCreator(ShiroUser.getInstance().getUser().getUsername());
			activityService.save(lottery);
			List<LotteryPrize> prizeList =lottery.getPrizeList();
			if(prizeList.size()>0){
				//总的随机数记录
				List<Integer> orderlucknumList = new LinkedList<Integer>(); 
				for (LotteryPrize lotteryPrize : prizeList) {
					//保存该活动的奖品
					lotteryPrize.setLotteryactivity(lottery);
					lotteryPrize.setCorp(new Corporation(corpid));
					lotteryPrize.setCreator(ShiroUser.getInstance().getUser().getUsername());
					lotteryPrize.setCreatTime(new Date());
					lotteryPrize.setStock(lotteryPrize.getMaxsum());
					int lucknum = RandomLotteryLuckNum.randomLuckNum(0, 0, orderlucknumList, lotteryPrize.getProbability());
					orderlucknumList.add(lucknum);
					lotteryPrize.setLucknum(lucknum);
					lotteryPrize.setLucknumber(0);
					lotteryPrize.setOrderlucknum(String.valueOf(lucknum));
					lotteryPrize.setOrdernum(0);
					iLotteryPrizeService.save(lotteryPrize);
				}
			}
 			return "redirect:/manage/lottery/list";
		} catch (Exception e) {
			return "system/500";
		}
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable Long id, RedirectAttributes redirectAttributes) {
		try {
			activityService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/lottery/list";
		} catch (Exception e) {
			logger.error("删除错误,id=" + id, e);
			return "system/500";
		}
	}
	/**查看该活动*/
	@RequestMapping(value="/info/{id}")
	public String toinfo(@PathVariable Long id,Model model){
		try {
			model.addAttribute("scoretypeList", LotteryPurposeEnums.values());
			model.addAttribute("typeList", LotteryActivityTypeEnums.values());
			model.addAttribute("statusList", LotteryActivityStatusEnums.values());
			model.addAttribute("prizetypeList",LotteryActivityPrizeEnums.values());
			LotteryActivity activity =  activityService.get(id);
			model.addAttribute("activity", activity);
			return "lottery/info";
		} catch (Exception e) {
			return "system/500";
		}
		
	}
	/**查看该活动*/
	@RequestMapping(value="/update/{id}")
	public String toupdate(@PathVariable Long id,Model model){
		try {
			model.addAttribute("scoretypeList", LotteryPurposeEnums.values());
			model.addAttribute("typeList", LotteryActivityTypeEnums.values());
			model.addAttribute("statusList", LotteryActivityStatusEnums.values());
			model.addAttribute("prizetypeList",LotteryActivityPrizeEnums.values());
			LotteryActivity activity =  activityService.get(id);
			model.addAttribute("activity", activity);
			return "lottery/update";
		} catch (Exception e) {
			return "system/500";
		}
		
	}
	
	@RequestMapping(value="update",method=RequestMethod.POST)
	public String update(Model model,LotteryActivity lottery){
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			if(lottery.getStatus()== LotteryActivityStatusEnums.NORMAL.getValue()){
				/**停用所有其他的抽奖活动*/
				List<LotteryActivity> activityList=activityService.findByCorpIdAndStatus(corpid,LotteryActivityStatusEnums.NORMAL.getValue());
				if(activityList.size()>0){
					for (LotteryActivity lotteryActivity : activityList) {
						lotteryActivity.setStatus(LotteryActivityStatusEnums.STOP.getValue());
						activityService.save(lotteryActivity);
					}
				}
			}
			activityService.save(lottery);
			List<LotteryPrize> prizeList =lottery.getPrizeList();
			if(prizeList.size()>0){
				for (LotteryPrize lotteryPrize : prizeList) {
					/**查询奖品*/
					LotteryPrize prize= iLotteryPrizeService.get(lotteryPrize.getId());
					/**如果奖品的数量改变了则更新库存*/
					if(prize.getStock()!=lotteryPrize.getStock()){
						/**如果是减少了*/
						if(prize.getStock()>lotteryPrize.getStock()){
							int num = prize.getStock()-lotteryPrize.getStock();
							lotteryPrize.setMaxsum(lotteryPrize.getMaxsum()-num);
						}else{
							int num = lotteryPrize.getStock()-prize.getStock();
							lotteryPrize.setMaxsum(lotteryPrize.getMaxsum()+num);
						}
					}
					/**如果更新了中奖概率*/
					if(prize.getProbability()!=lotteryPrize.getProbability()){
						/**得到已经抽奖的次数*/
						int num = iLotteryRecordService.getLotteryRecodeNum(lottery.getId());
						/**更新中奖号码，随机初始数，更新中奖次数*/
						lotteryPrize.setLucknumber(0);
						lotteryPrize.setOrdernum(num);
						/**更新中奖号码*/
						List<Integer> orderlucknumList = new LinkedList<Integer>(); /** 该奖品所有中奖号码的集合 */
						String s_ordernum = lotteryPrize.getOrderlucknum();
						String[] ordernumList = s_ordernum.split(",");
						/** 转换成数字存到所有中奖号码的集合 */
						for (int i = 0; i < ordernumList.length; i++) {
							orderlucknumList.add(Integer.valueOf(ordernumList[i]));
						}
						int u_lucknum = RandomLotteryLuckNum.randomLuckNum(lotteryPrize.getLucknumber(), lotteryPrize.getOrdernum(),
								orderlucknumList, lotteryPrize.getProbability());
						lotteryPrize.setLucknum(u_lucknum);
					}
					lotteryPrize.setLotteryactivity(lottery);
					lotteryPrize.setCorp(lottery.getCorp());
					iLotteryPrizeService.save(lotteryPrize);
				}
			}
 			return "redirect:/manage/lottery/list";
		} catch (Exception e) {
			return "system/500";
		}
	}
}
